document.addEventListener('DOMContentLoaded', () => {
  const lengthInput = document.getElementById('length');
  const generateButton = document.getElementById('generate');
  const passwordDisplay = document.getElementById('password');
  const historyDiv = document.getElementById('history');

  // 初始化时加载历史记录
  loadHistory();

  // 定时刷新历史记录
  setInterval(loadHistory, 1000); // 每5秒刷新一次

  // 生成并复制密码
  generateButton.addEventListener('click', () => {
    const length = parseInt(lengthInput.value, 10);
    const password = generatePassword(length);
    passwordDisplay.textContent = password;
    copyToClipboard(password);
  });

  // 生成随机密码
  function generatePassword(length) {
    const charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()_+";
    let password = "";
    for (let i = 0; i < length; i++) {
      password += charset.charAt(Math.floor(Math.random() * charset.length));
    }
    return password;
  }

  // 复制到剪贴板
  async function copyToClipboard(text) {
    try {
      await navigator.clipboard.writeText(text);
      // 获取当前时间
      const timestamp = new Date().toISOString();
      // 向 background 脚本发送消息保存密码
      chrome.runtime.sendMessage({
        action: 'savePassword',
        data: { password: text, timestamp }
      });

      // 引入 Chrome 通知 API
      chrome.notifications.create('passwordCopied', {
        type: 'basic',
        iconUrl: 'icon16.png', // 通知图标路径
        title: '密码已复制',
        message: '密码已成功复制到剪贴板！',
        priority: 1
      }, function(notificationId) {
        // 可以在这里处理通知创建后的逻辑
      });
    } catch (err) {
      console.error('Failed to copy to clipboard: ', err);
    }
  }

  // 加载历史记录
  function loadHistory() {
    chrome.runtime.sendMessage({ action: 'getPasswordHistory' }, response => {
      if (response && response.history) {
        const historyList = response.history.map(entry => `<p>${entry.password} - ${entry.timestamp}</p>`).join('');
        historyDiv.innerHTML = historyList;
      } else {
        historyDiv.textContent = 'No history available.';
      }
    });
  }
});